<template>
  <view class="feedback-container">
    <view class="feedback-form">
      <view class="form-item">
        <text class="label">反馈类型</text>
        <view class="type-selector">
          <view 
            v-for="type in feedbackTypes" 
            :key="type.value"
            class="type-item"
            :class="{ active: selectedType === type.value }"
            @click="selectedType = type.value"
          >
            {{ type.label }}
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="label">反馈内容</text>
        <textarea
          v-model="content"
          class="content-input"
          placeholder="请详细描述您遇到的问题或建议..."
          maxlength="500"
        />
        <text class="word-count">{{ content.length }}/500</text>
      </view>

      <view class="form-item">
        <text class="label">联系方式（选填）</text>
        <input
          v-model="contact"
          class="contact-input"
          placeholder="请留下您的手机号或邮箱"
        />
      </view>

      <!-- 位置选择（仅问题投诉时显示） -->
      <view v-if="selectedType === 2" class="form-item">
        <text class="label">位置信息（选填）</text>
        <view class="location-section">
          <view class="location-info" @click="openLocationPicker">
            <view class="location-text">
              <text v-if="location.address" class="address">{{ location.address }}</text>
              <text v-else class="placeholder">点击选择位置</text>
            </view>
            <text class="location-icon">📍</text>
          </view>
          <button class="locate-btn" @click="getCurrentLocation">定位</button>
        </view>
      </view>

      <view class="form-item">
        <text class="label">上传截图（选填）</text>
        <view class="image-uploader">
          <view 
            v-for="(image, index) in images" 
            :key="index"
            class="image-item"
          >
            <image :src="image" mode="aspectFill" class="preview-image" />
            <text class="delete-btn" @click="deleteImage(index)">×</text>
          </view>
          <view 
            v-if="images.length < 3" 
            class="upload-btn"
            @click="chooseImage"
          >
            <text class="upload-icon">+</text>
          </view>
        </view>
      </view>
    </view>

    <button class="submit-btn" @click="submitFeedback">提交反馈</button>
    
    <Loading :show="isLoading" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { uploadAvatar } from '@/api/oss';
import { addFeedback } from '@/api/user';
import { feedbackContentVerification } from '@/api/ai';
import { getLocationByIp } from '@/api/map';
import Loading from '@/components/Loading.vue';
import { onShow } from '@dcloudio/uni-app';

const feedbackTypes = [
  { label: '功能建议', value: 1 },
  { label: '问题投诉', value: 2 },
  { label: '其他', value: 3 }
];

const selectedType = ref(1);
const content = ref('');
const contact = ref('');
const images = ref<string[]>([]);
const isLoading = ref(false);
const location = ref<{
  address?: string;
  latitude?: number;
  longitude?: number;
}>({});

// 页面加载时获取IP定位
onMounted(() => {
  if (selectedType.value === 2) {
    getCurrentLocation();
  }
});

// 监听类型切换，问题投诉时自动定位，其他类型清空地址
watch(selectedType, (newVal) => {
  if (newVal === 2) {
    getCurrentLocation();
  } else {
    location.value = {};
  }
});

// 页面显示时读取本地缓存的选中位置
onShow(() => {
  const cache = uni.getStorageSync('selectedLocation');
  if (cache && cache._ts && Date.now() - cache._ts < 5 * 60 * 1000) {
    updateLocation(cache);
    uni.removeStorageSync('selectedLocation');
  } else if (cache) {
    uni.removeStorageSync('selectedLocation');
  }
});

const chooseImage = () => {
  uni.chooseImage({
    count: 3 - images.value.length,
    success: (res) => {
      images.value = [...images.value, ...res.tempFilePaths];
    }
  });
};

const deleteImage = (index: number) => {
  images.value.splice(index, 1);
};

// 获取当前位置（IP定位）
const getCurrentLocation = async () => {
  try {
    uni.showLoading({ title: '定位中...' });
    
    // 使用后端API进行IP定位
    const response = await getLocationByIp();
    
    if (response.code === 200 && response.data) {
      const data = response.data;
      
      // 根据后端返回的数据格式设置位置信息
      if (data.latitude && data.longitude) {
        location.value = {
          address: data.formattedAddress || data.address || '未知地址',
          latitude: parseFloat(data.latitude),
          longitude: parseFloat(data.longitude)
        };
      } else if (data.rectangle) {
        // 如果返回的是矩形区域，取中心点
        const coords = data.rectangle.split(';')[0].split(',');
        const longitude = parseFloat(coords[0]);
        const latitude = parseFloat(coords[1]);
        
        location.value = {
          address: data.formattedAddress || data.address || '未知地址',
          latitude,
          longitude
        };
      }
    }
  } catch (error) {
    console.error('获取位置失败:', error);
    uni.showToast({
      title: '定位失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 打开位置选择页面
const openLocationPicker = () => {
  uni.navigateTo({
    url: '/pages/settings/location-picker'
  });
};

// 更新位置信息（供位置选择页面调用）
const updateLocation = (locationData: any) => {
  console.log(locationData)
  if (locationData) {
    location.value = {
      address: locationData.address,
      latitude: locationData.latitude,
      longitude: locationData.longitude
    };
    
    // 如果选择了售货机，可以显示额外信息
    if (locationData.type === 'machine' && locationData.machineInfo) {
      location.value.address = `${locationData.machineInfo.deviceName} - ${locationData.address}`;
    }
  }
};

const submitFeedback = async () => {
  if (!content.value.trim()) {
    uni.showToast({
      title: '请输入反馈内容',
      icon: 'none'
    });
    return;
  }

  try {
    isLoading.value = true;

    // 先进行内容验证
    const contentType = feedbackTypes.find(type => type.value === selectedType.value)?.label || '其他';
    
    // 获取用户信息
    const userInfo = uni.getStorageSync('userInfo');
    
    // 如果有图片，使用第一张图片进行验证
    let imagePath = null;
    if (images.value.length > 0) {
      imagePath = images.value[0]; // 使用第一张图片进行验证
    }

    const verificationResult = await feedbackContentVerification(imagePath, content.value, contentType, userInfo.id);
    // 检查验证结果
    if (verificationResult.data === "False" || verificationResult.data === "false") {
      uni.showToast({
        title: verificationResult.msg || '内容验证失败，请检查内容后重试',
        icon: 'none',
        duration: 3000
      });
      return;
    }

    // 上传图片，收集ossId
    let ossIds: string[] = [];
    for (const filePath of images.value) {
      const res = await uploadAvatar(filePath) as any;
      ossIds.push(res.data.ossId);
    }

    // 提交反馈
    await addFeedback({
      userId: userInfo.id,
      feedbackType: selectedType.value,
      content: content.value,
      contact: contact.value,
      image: ossIds.join(','),
      latitude: location.value.latitude,
      longitude: location.value.longitude
    });

    uni.showToast({
      title: '提交成功',
      icon: 'success'
    });
    
    // 清空表单
    content.value = '';
    contact.value = '';
    images.value = [];
    selectedType.value = 1;
    
    // 跳转到反馈回复页面
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/settings/feedbackReply'
      });
    }, 1500);
  } catch (error) {
    console.error('提交反馈失败:', error);
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};
</script>

<style>
.feedback-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.feedback-form {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.type-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.type-item {
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #666;
  background-color: #f5f5f5;
}

.type-item.active {
  color: #ffffff;
  background-color: #007aff;
}

.content-input {
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.word-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  margin-top: 10rpx;
}

.contact-input {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.image-uploader {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  top: -20rpx;
  right: -20rpx;
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  border-radius: 50%;
  font-size: 32rpx;
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  font-size: 60rpx;
  color: #999;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #007aff;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 40rpx;
}

.location-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.location-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.location-text {
  flex: 1;
}

.address {
  font-size: 28rpx;
  color: #333;
}

.placeholder {
  font-size: 28rpx;
  color: #999;
}

.location-icon {
  font-size: 28rpx;
  color: #666;
}

.locate-btn {
  padding: 10rpx 20rpx;
  background-color: #007aff;
  color: #ffffff;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.location-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.location-content {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  width: 80%;
  max-width: 600rpx;
}

.location-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.title {
  font-size: 28rpx;
  color: #333;
}

.close {
  font-size: 28rpx;
  color: #666;
}

.location-body {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.search-box {
  position: relative;
}

.search-input {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.location-list {
  max-height: 300rpx;
  overflow-y: auto;
}

.location-item {
  padding: 10rpx 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.item-name {
  font-size: 28rpx;
  color: #333;
}

.item-address {
  font-size: 24rpx;
  color: #999;
}
</style> 